<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="btnController">
        <el-button class="buttons" @click=";(dialogFormVisible = true), (dialogStatus = 'create')">
          添加
        </el-button>
      </div>
      <div class="formContainer">
        <label class="filterLabel">关键词 :</label>
        <el-input v-model="listQuery.keyword" clearable placeholder="请输入" class="filterInput" @keyup.enter.native="handleFilter" />
        <el-button class="buttons" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
      </div>
    </div>
    <el-table :key="tableKey" :header-cell-style="{ background: '#ebebeb', height: '#54px' }" :data="list" style="width: 100%;" @sort-change="sortChange">
      <el-table-column label="序号" type="index" sortable="custom" align="center" width="80" :class-name="getSortClass('id')" />
      <el-table-column label="用户名" align="center">
        <template slot-scope="{ row }">
          {{ row.username }}
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center">
        <template slot-scope="{ row }">
          {{ row.type }}
        </template>
      </el-table-column>
      <el-table-column label="积分" align="center">
        <template slot-scope="{ row }">
          {{ row.value }}
        </template>
      </el-table-column>
      <el-table-column label="时间" align="center">
        <template slot-scope="{ row }">
          {{ row.addtime }}
        </template>
      </el-table-column>
      <el-table-column v-if="false" label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{ row, $index }">
          <el-button
            type="primary"
            size="mini"
            @click="
              $router.push({
                name: 'UsersAdd',
                query: {
                  id: row.id
                }
              })
            "
          >
            编辑
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="
              $router.push({
                name: 'SubList',
                query: {
                  enterprise_id: row.id
                }
              })
            "
          >
            账号管理
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="
              $router.push({
                name: 'AddressIndex',
                query: {
                  enterprise_id: row.id
                }
              })
            "
          >
            地址列表
          </el-button>
          <el-popconfirm v-if="false" confirm-button-text="好的" cancel-button-text="不用了" icon="el-icon-info" icon-color="red" title="删除后不可以恢复，确定删除吗？" @onConfirm="handleDelete(row, $index)">
            <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.per_page" @pagination="getList" />
    <!-- 编辑、 添加弹框表单 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="rows" label-position="right" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="昵称" prop="nickname" class="marginTop30">
          <el-input v-model="rows.nickname" placeholder="请填写企业名称" />
        </el-form-item>
        <el-form-item label="企业类型" prop="member_type" class="marginTop30">
          <el-select v-model="rows.member_type" style="width: 260px;" clearable placeholder="请选择">
            <el-option v-for="(types, index) in enterpriseTypes" :key="index" :label="types" :value="index">{{ types }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="rows.username" autocomplete="new-password" placeholder="请填写用户名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile" class="marginTop30">
          <el-input v-model="rows.mobile" maxlength="11" autocomplete="new-password" placeholder="请填写手机号码" />
        </el-form-item>
        <div>
          <el-form-item label="密码" class="marginTop30" prop="password">
            <el-input v-model="rows.password" type="password" autocomplete="new-password" placeholder="请填写密码" />
          </el-form-item>
          <el-form-item label="确认密码" class="marginTop30" autocomplete="new-password" prop="passwordA">
            <el-input v-model="rows.passwordA" type="password" placeholder="请再次填写密码" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
    <!--  -->
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { userScore, add, edit, del, rows, handleBefore } from '@/api/user'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { notifySuccess, notifyError } from '@/utils/message'
import { getIP } from '@/utils/index'

export default {
  name: 'UsersIndex',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        normal: '正常',
        hidden: '隐藏'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      enterpriseTypes: null,
      expandAll: false,
      checkedKeys: [],
      tableKey: 0,
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        per_page: 15,
        keyword: '',
        keywordb: '',
        type: null,
        isverify: null,
        sort: '+id',
        addtimestart: 0,
        addtimeend: 0,
        mobile: null,
        tel: null
      },
      dataRange: [],
      importanceOptions: [1, 2, 3],
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: { normal: '正常', hidden: '隐藏' },
      showReviewer: false,
      rows: {
        id: '',
        member_type: null,
        mobile: '',
        username: '',
        enterprise_name: '',
        password: '',
        passwordA: '',
        ip: '',
        agent: 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        member_type: [{ required: true, message: '企业类型', trigger: 'change' }],
        mobile: [{ required: true, message: '不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        username: [{ required: true, message: '不能为空', trigger: 'blur' }],
        enterprise_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '不能为空', trigger: 'blur' }],
        passwordA: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      groupOption: {},
      handleInfos: {}
    }
  },
  created() {
    if (this.$route.params.keyword || this.$route.query.keyword) {
      this.listQuery.keyword = this.$route.params.keyword ? this.$route.params.keyword : this.$route.query.keyword
    }
    this.getList()
    this.handleInfo()
  },
  methods: {
    // 获取列表数据
    getList() {
      var that = this
      this.listLoading = true
      const kw = this.listQuery.keyword
      this.listQuery.keyword = kw.trim()
      userScore(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          that.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetRows() {
      this.rows = {
        member_type: null,
        mobile: '',
        username: '',
        enterprise_name: '',
        password: '',
        passwordA: '',
        ip: '',
        agent: ''
      }
    },
    handleCreate() {
      this.resetRows()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    openIng() {
      notifyError('开发中')
    },
    // 新增提交方法
    async createData() {
      const that = this
      const ipaddres = await getIP()
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          add(that.rows.mobile, that.rows.username, that.rows.enterprise_name, that.rows.password, that.rows.passwordA, ipaddres, that.rows.agent, that.rows.member_type).then((response) => {
            // that.list.unshift(this.temp)
            that.dialogFormVisible = false
            notifySuccess('新增成功')
            that.getList()
          })
        }
      })
    },
    // 编辑数据
    handleUpdate(row) {
      const that = this
      this.roledata.id = row.id
      rows(row.id).then(function(res) {
        that.rows = Object.assign({}, res.data) // copy obj
        that.rows.ids = row.id
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.rows)
          edit(tempData.id, tempData.pid, tempData.name, tempData.status, tempData.rules).then((res) => {
            const index = that.list.findIndex((v) => v.id === that.rows.ids)
            that.list.splice(index, 1, that.rows)
            that.dialogFormVisible = false
            notifySuccess(res.msg || '编辑成功')
          })
        }
      })
    },
    // 删除操作
    handleDelete(row, index) {
      // var that = this
      del(row.id).then((res) => {
        notifySuccess(res.msg || '删除成功')
        this.getList()
        // that.list.splice(index, 1)
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    // 处理前数据
    handleInfo() {
      handleBefore().then((res) => {
        this.handleInfos = res.data
        this.enterpriseTypes = res.data.enterprise_member_type
      })
    },
    // 行内搜索
    lineSearch(column, val) {
      this.listQuery[column] = val
      this.getList()
    }
  }
}
</script>
<style scoped>
.main-success {
  color: #409eff;
}
.main-error {
  color: #e6a23c;
}
</style>
